# -*- coding: utf-8 -*-

############################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#############################################################################

"""
Common tools and methods 

"""

import os
import datetime as dt
import sys
import re
import psutil
import time
from pymediainfo import MediaInfo
from utils.wraps import token

# 公共函数

def ip_check(ipAddr):
    compile_ip = re.compile(
        r'^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.'
        r'(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.'
        r'(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.'
        r'(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$')
    if compile_ip.match(ipAddr):
        return True
    else:
        return False


def is_valid_domain(value):
   


    pattern = re.compile(
        r'^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|'
        r'([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|'
        r'([a-zA-Z0-9][-_.a-zA-Z0-9]{0,61}[a-zA-Z0-9]))\.'
        r'([a-zA-Z]{2,13}|[a-zA-Z0-9-]{2,30}.[a-zA-Z]{2,3})$'
    )
    if pattern.match(value):
        return True
    else:
        return False


def ping(value):



    cmd = 'ping {} -c 2 -W 2 '.format(value)
    cmd_str = os.popen(cmd).readlines()
    for line in cmd_str:
        if '100% packet loss' in line or 'unknown host' in line:
            return False
    return True


def utcday():

    return (dt.datetime.utcnow()).strftime('%F')


def localtime():


    return (dt.datetime.now()).strftime('%F %T')


def localdate_file():
  

    return (dt.datetime.now()).strftime('%F-%H-%M-%S-%f')


def utcnow_ymd():


    return (dt.datetime.utcnow()).strftime('%Y%m%d')


def utcndayago(agoday):


    return (dt.datetime.utcnow() - dt.timedelta(days=agoday)).strftime('%F')


def utcndayafter(afterday):


    return (dt.datetime.utcnow() + dt.timedelta(days=afterday)).strftime('%F')


def utcndayago_ymd(agoday):


    return (dt.datetime.utcnow() - dt.timedelta(days=agoday)).strftime('%Y%m%d')


def utcndayafter_ymd(afterday):


    return (dt.datetime.utcnow() + dt.timedelta(days=afterday)).strftime('%Y%m%d')


def hidertsp_pwd(rtsp: str):
  


    p = rtsp.split('@')
    return 'rtsp://***:***@{}'.format(p[1])


def make_flvuri(ids):
   
    return '/live/{}.flv'.format(ids)


def make_rtmpuri(ids):

    return '/live/{}'.format(ids)


def getexepath():
    """获取程序路径"""

    return os.path.split(os.path.realpath(sys.argv[0]))[0]


def check_str(name):
    """"""
    special_str = re.search(r"\W", name)
    if special_str is None:
        return True
    else:
        return False


def proc_exist(process_name):

    pl = psutil.pids()
    for pid in pl:
        if psutil.Process(pid).name() == process_name:
            if isinstance(pid, int):
                return True
    return False

def get_video_duration(video) -> float:

    media_info = MediaInfo.parse(video)
    for track in media_info.tracks:
        if track.track_type == "Video":
            # print("Duration (seconds):", track.duration / 1000.0)
            return track.duration / 1000.0 
        
def time_data(time_sj):      
    data_sj = time.localtime(time_sj)
    time_str = time.strftime("%Y-%m-%d",data_sj)          
    return time_str       

import socket

def get_host_ip():

    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(('8.8.8.8',80)) # 8.8.8.8是一个IP地址,是Google提供的免费DNS服务器的IP地址
        ip=s.getsockname()[0]
    finally:
        s.close()

    return ip